import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'

// create an axios instance
const service = axios.create({
  // ! 配置请求头
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      // ! 配置token
      config.headers['X-Token'] = store.getters.token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(

  response => {
    const { data, errmsg, errno } = response.data
    if (errno === 0) {
      return data
    } else {
      if (errno === 9997) {
        Message({ type: 'error', message: errmsg })
        store.dispatch('user/logoutAction')
        router.push('/login')
        return Promise.reject(new Error(errmsg))
      }
      Message({ type: 'error', message: errmsg })
      return Promise.reject(new Error(errmsg))
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error'

    })
    return Promise.reject(error)
  }
)

export default service
